<template>
  <div class="main-bg">
    <el-form ref="form" :model="queryParams" :inline="true" size="small">
      <el-form-item label="手机号：" prop="goodsName" >
        <el-input v-model="queryParams.goodsName" clearable="" placeholder="手机号"></el-input>
      </el-form-item>

      <div style="float: right;">
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </div>



    </el-form>
    <div class="container">
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column
          prop="goodsCode"
          align="center"
          label="昵称">
        </el-table-column>
        <el-table-column
          prop="goodsName"
          align="center"
          label="手机号">
        </el-table-column>



      </el-table>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="pageNum"
        style="float: right;margin-top: 20px;"
        :page-sizes="[10, 20, 50, 100]"

        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!--查看-->
      <el-dialog title="查看详情" top="6vh" :visible.sync="seeFlag"  width="70%" append-to-body>
        <el-descriptions  :column="2"  border  class="my-label">
          <el-descriptions-item label="商品编号">{{form.goodsCode}}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{form.goodsName}}</el-descriptions-item>
          <el-descriptions-item label="品牌">{{form.brandName}}</el-descriptions-item>
          <el-descriptions-item label="单位">{{form.unitsName}}</el-descriptions-item>
          <el-descriptions-item label="一级分类">{{form.classifyOneName}}</el-descriptions-item>
          <el-descriptions-item label="二级分类">{{form.classifyTwoName}}</el-descriptions-item>
          <el-descriptions-item label="采购金额">{{form.realityPrice}}</el-descriptions-item>
          <el-descriptions-item label="售卖金额">{{form.discountsPrice}}</el-descriptions-item>
          <el-descriptions-item label="库存">{{form.inventoryAmount}}</el-descriptions-item>
          <el-descriptions-item label="状态">{{form.goodsStatus==1002?'上架':'下架'}}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions  :column="1"  border  class="my-label">
          <el-descriptions-item label="标签">{{form.tagsNames}}</el-descriptions-item>
          <el-descriptions-item label="备注">{{form.remark}}</el-descriptions-item>


          <el-descriptions-item label="规格参数">
            <el-table :data="groupParams" style="width: 100%;margin-top: 20px;">
              <el-table-column prop="paramsSort" align="center" label="排序">
              </el-table-column>
              <el-table-column prop="paramsKey" align="center" label="参数名称">
              </el-table-column>
              <el-table-column prop="paramsValue" align="center" label="参数值">
              </el-table-column>
              <el-table-column prop="paramsUnit" align="center" label="单位">
              </el-table-column>
            </el-table>
          </el-descriptions-item>
        </el-descriptions>
        <el-carousel trigger="click" type="card" height="2  00px" >
          <el-carousel-item v-for="item in form.imageUrls" :key="item">
            <img :src="item" style="width: 100%;height:100%" alt="">
          </el-carousel-item>
        </el-carousel>
      </el-dialog>

      <!--编辑-->
      <el-dialog title="编辑" top="6vh" :visible.sync="editFlag"  width="70%" append-to-body class="my-label">
        <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="标签" prop="tagsNames">
            <el-select v-model="editForm.tags" @change="selectChangeMethod" multiple clearable filterable allow-create style="width:100%" placeholder="请选择">
              <el-option
                v-for="item in tagsList"
                :key="item.tagsId"
                :label="item.tagsName"
                :value="item.tagsId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="售卖金额" prop="discountsPrice">
            <el-input v-model="editForm.discountsPrice"></el-input>
          </el-form-item>
          <el-form-item label="采购金额" prop="realityPrice">
            <el-input v-model="editForm.realityPrice"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editForm.remark"></el-input>
          </el-form-item>
          <el-form-item style="text-align: right">
            <el-button type="primary" @click="submitForm('editForm')">确定</el-button>
            <el-button @click="editFlag=false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <el-dialog :visible.sync="dialogTableVisible">
        <el-descriptions title="规格参数" :column="2"  border>
          <el-descriptions-item v-for="item in ParamsData" :label="item.paramsKey">{{item.paramsValue+item.paramsUnit}}</el-descriptions-item>

        </el-descriptions>
      </el-dialog>

      <el-dialog title="下单" :visible.sync="dialogFormVisible" width="1000px">
        <el-form :model="addorderData" :rules="saveFormRules"  ref="dataForm" label-width="100px">
          <el-form-item label="客户/地址" prop="buyData">
            <el-select v-model="addorderData.buyData" value-key="buyId"  filterable style="width:100%" @change="changeClassifyTwo" clearable
                       placeholder="请选择" >
              <el-option v-for="item in addressList" :key="item.buyId" :label="item.buyName+'/'+item.buyPhone+'/'+item.buyAddress"
                         :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="categoryId" label="一级分类:" style="width:100%" >
            <el-select v-model="addorderData.categoryId"  style="width:100%" clearable
                       placeholder="请选择" @change="categoryChange">
              <el-option v-for="item in classifyArr" :key="item.categoryId" :label="item.categoryName"
                         :value="item.categoryId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="classifyTwoId" label="二级分类:" style="width:100%" >
            <el-select v-model="addorderData.classifyTwoId"  style="width:100%" @change="changeClassifyTwo" clearable
                       placeholder="请选择" >
              <el-option v-for="item in classifyArrTwo" :key="item.categoryId" :label="item.categoryName"
                         :value="item.categoryId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="goodsId" label="选择商品:" style="width:100%" >
            <el-select v-model="addorderData.goodsId" style="width:100%" @change="searchSelect" value-key="goodsId" multiple filterable clearable
                       placeholder="请选择" >
              <el-option v-for="item in goodsList" :disabled="item.inventoryAmount==0" :key="item.goodsId" :label="item.goodsName"
                         :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="已选商品">
            <!--          <el-button size="mini" @click="giftOpen" v-if="formType === 'ADD'">选择商品</el-button>-->
            <el-table :data="addorderData.orderGoodsBos" v-if="addorderData.orderGoodsBos.length > 0" border  style="width: 100%;margin-top: 20px;">
              <el-table-column label="序号" prop="index" width="50px" align="center" header-align="center">
                <template slot-scope="scope">
                  {{scope.$index+1}}
                </template>
              </el-table-column>

              <el-table-column label="商品名称" prop="goodsName" align="center" header-align="center"></el-table-column>
              <el-table-column label="规格名称" prop="groupName" align="center" header-align="center"></el-table-column>
              <el-table-column label="数量" prop="goodsPrice" align="center">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.totalAmount" :min="1"  label="数量"></el-input-number>
                </template>
              </el-table-column>

            </el-table>
          </el-form-item>
          <el-form-item prop="remark" label="备注:" style="width:100%" >
            <el-input v-model="addorderData.remark"></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible=false">取 消</el-button>
          <el-button type="primary" @click="submitOrder('dataForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { getParentCategoryAll} from "@/api/commodity/commodityClassification";
  import {
    getInventoryGoodsStatusPageList,
    getInventoryGoodsDetails,
    getTagsAll,
    updateInventoryStatus,
    getInventoryGoodsPageList
  } from '@/api/stock'
  import { getBrandAll} from "@/api/commodity/commodityBrand";
  import { getGoodsPageList, getPurchaseDetails } from '@/api/purchaseManagement/purchaseList/purchaseList'
  import { getSonCategoryByParent,getWholesaleBuyStatusAll,saveOrder } from '@/api/commodity/commodityTemplate'
  export default {
    name: "InventoryManage",
    data(){
      return{
        dialogFormVisible:false,
        dialogTableVisible:false,
        ParamsData:{},
        seeFlag:false,
        goodsStatusArr:[{
          brandId:1002,
          brandName:'上架',
        },{
          brandId:1020,
          brandName:'下架',
        }],
        categoryList: [],
        queryParams:{},
        pageNum:1,
        total:0,
        loading:true,
        checked:false,
        tableData:[],
        brandList:[],
        form:{},
        groupParams:[],
        editFlag:false,
        editForm:{},
        classifyArr: [],
        classifyArrTwo: [],
        goodsList: [],
        addressList:[],
        tagsList:[],
        addorderData: {
          buyData:'',
          buyAddress:'',
          buyName:'',
          buyPhone:'',
          goodsId:'',
          orderStatus:2101,
          //规格参数List
          orderGoodsBos: []
        },
        rules:{
          discountsPrice: [
            { required: true, message: '请输入售卖金额', trigger: 'blur' },
          ],
          realityPrice: [
            { required: true, message: '请输入采购金额', trigger: 'blur' },
          ],
        },
        saveFormRules: {
          buyData: {
            required: true, message: '请选择客户/地址', trigger: 'change'
          },
          categoryId: {
            required: true, message: '请选择一级分类', trigger: 'change'
          },
          classifyTwoId: {
            required: true, message: '请选择二级分类', trigger: 'change'
          },
          goodsId: {
            required: true, message: '请选择商品', trigger: 'change'
          },
        },
      }
    },
    mounted(){
      this.getList()
      this.getBrand()
      this.getClassify()
      this.getParentCategoryAllSelectList()
      this.getWholesaleBuyStatusAll()
    },
    methods:{
      changeClassifyTwo(){
        this.getGoodsList()
      },
      searchSelect(val){

        this.addorderData.orderGoodsBos=val
      },
      // 获取商品列表
      getGoodsList() {
        let body = {
          pageSize: 10000,
          pageNum: 1,
          table: {
            "classifyTwoId": this.addorderData.classifyTwoId, //一级分类id
            "storeCoding": localStorage.getItem('storeCoding')
          }
        }
        getInventoryGoodsStatusPageList({ body }).then(res => {
          this.goodsList = res.body.list

        })

      },
      // 分类触发规格
      async categoryChange(val) {
        let body = {
          "parentId": val,
          "storeCoding": localStorage.getItem('storeCoding') //门店识别号
        }
        await getSonCategoryByParent({ body }).then(res => {
          this.classifyArrTwo = res.body

        })
      },
      // 分类下来
      async getParentCategoryAllSelectList() {
        let body = {
          "storeCoding": localStorage.getItem('storeCoding') //门店识别号
        }
        await getParentCategoryAll({ body }).then(res => {
          this.classifyArr = res.body

        })
      },
      // 获取地址列表
      async getWholesaleBuyStatusAll() {
        let body = {
          "storeCoding": localStorage.getItem('storeCoding') //门店识别号
        }
        await getWholesaleBuyStatusAll({ body }).then(res => {
          this.addressList = res.body

        })
      },
      addOrder(){
        this.addorderData={
          buyData:'',
            buyAddress:'',
            buyName:'',
            buyPhone:'',
          orderStatus:2101,
            goodsId:[],
            //规格参数List
            orderGoodsBos: []
        }
        this.dialogFormVisible=true
      },
      // 查看参数
      checkParams(data){
        var arr=JSON.parse(data);
        this.ParamsData=arr
        console.log(this.ParamsData)
        this.dialogTableVisible=true
      },
      selectChangeMethod(){
        this.$forceUpdate()
      },
      // 上下架
      async updateStatus(row){
        let body={
          inventoryId:row.inventoryId,
          discountsPrice:row.discountsPrice,
          goodsStatus:row.goodsStatus==1020?'1002':1020,
          storeCoding: localStorage.getItem('storeCoding')
        }
        let res = await updateInventoryStatus({body})
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
        this.getList()
      },
      submitOrder(formName){

        this.$refs[formName].validate((valid) => {
          if (valid) {
            for(let i=0;i<this.addorderData.orderGoodsBos.length;i++){
              this.addorderData.orderGoodsBos[i].goodsType=1301
              this.addorderData.orderGoodsBos[i].activityInventoryId=''
              if(this.addorderData.orderGoodsBos[i].totalAmount<=0||this.addorderData.orderGoodsBos[i].totalAmount==''||this.addorderData.orderGoodsBos[i].totalAmount==undefined||this.addorderData.orderGoodsBos[i].totalAmount==null){
                this.$message({
                  message: '第'+(i+1)+'组商品必须大于1，请检查！',
                  type: 'error',
                });
                return  false
              }
            }
            this.addorderData.buyAddress=this.addorderData.buyData.buyAddress
            this.addorderData.buyName=this.addorderData.buyData.buyName
            this.addorderData.buyPhone=this.addorderData.buyData.buyPhone
            console.log(this.addorderData)
            let body={
              ...this.addorderData
            }
            saveOrder({ body }).then(res => {
              this.$message({
                type: 'success',
                message: '下单成功!'
              });
              this.dialogFormVisible=false
            })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 编辑提交
      submitForm(formName){
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            console.log(this.editForm)
            var tagsNameArr=[]
            for (var i=0;i<this.editForm.tags.length;i++){
              for (var j=0;j<this.tagsList.length;j++){
                if(this.editForm.tags[i]==this.tagsList[j].tagsId){
                  tagsNameArr.push(this.tagsList[j].tagsName)
                }
              }
            }

            let body={
              ...this.editForm,
              tagsIds:this.editForm.tags.toString(),
              tagsNames:tagsNameArr.toString()
            }
            let res = await updateInventoryStatus({body})
            this.$message({
              type: 'success',
              message: '修改成功!'
            });

            this.getList()
            this.editFlag=false
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 查看详情
      async goDetail(row){
        let body={
          "inventoryId": row.inventoryId ,
          "storeCoding": localStorage.getItem('storeCoding')
        }
        let res = await getInventoryGoodsDetails({body})
        this.form=res.body
        this.groupParams=JSON.parse(this.form.groupParams)
        this.seeFlag=true
      },
      async editBtn(row){
        let body={
          "inventoryId": row.inventoryId ,
          "storeCoding": localStorage.getItem('storeCoding')
        }
        let res = await getInventoryGoodsDetails({body})
        this.editForm={...res.body}
        this.editForm.tags=res.body.tagsIds==''?'':res.body.tagsIds.split(',');
        this.getTags(row)


      },
      async getTags(row){
        let body={
          "storeCoding":  localStorage.getItem('storeCoding'),
          "categoryId": row.classifyOneId
        }
        let data = await getTagsAll({body})
        this.tagsList=data.body
        this.editFlag=true
      },
      // 获取品牌
      getBrand() {
        let body = {
          "storeCoding": localStorage.getItem('storeCoding')
        }
        getBrandAll({ body }).then(res => {
          this.brandList=res.body
        })

      },
      // 获取所有一级分类
      async getClassify(){
        let body={
          storeCoding:localStorage.getItem('storeCoding')
        }
        let res = await getParentCategoryAll({body})
        this.categoryList=res.body
      },
      async getList(){
        var that=this
        let body={
          pageSize:10,
          pageNum:this.pageNum,
          table:{
            storeCoding:localStorage.getItem('storeCoding'),
            ...this.queryParams,
            inventoryAmount:this.checked ? 1 : ''
          }
        }

        let res = await getInventoryGoodsPageList({body})
        that.tableData=res.body.list
        this.loading=false
        that.total=res.body.totalCount
      },
      handleQuery(){
        this.pageNum=1
        this.getList()
      },
      handleDelete(row){
        var that=this
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let body={
            incomeId:row.incomeId
          }
          axios.post('api/vegetable_income/deleteIncome',{
            body
          }).then(function (res) {

              if (res.data.code==2000){
                that.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                that.getList()
              }else{
                that.$message.error(res.data.msg);
              }
            }
          )

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });


      },

      timestampToTime(timestamp) {
        var time = this.dayjs(timestamp).format("YYYY-MM-DD");
        // var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        // var Y = date.getFullYear() + '-';
        // var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        // var D = date.getDate() + ' ';
        return time;
      },
      handleCurrentChange(val){
        this.pageNum=val
        this.getList()
      }
    },
  }
</script>

<style scoped>
  .titlebox{
    color:#20384D;
    font-size: 16px;
    display: flex;
    align-items: center;
    margin-bottom: 30px;
  }
  .titlebar{
    width: 4px;
    height: 16px;
    background: #035EBA;
    border-radius: 0 2px 2px 0;
    margin-right: 10px;
  }
  .titleline{
    flex: 1;
    height: 2px;
    background: #E6E9EE;
    margin-left: 20px;
  }
  .upload-tips{
    color: #999999;
    line-height: 20px;
  }
</style>
